/*
 RLRecyclingRunViewController.h
 Date Created: February 20, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "RLRecyclingRunViewController.h"

#import "RLStyleFormatter.h"
#import "RLRecyclableType.h"
#import "RLRecyclableItemButton.h"
#import "RLEditRecyclingRunViewController.h"

#import "GPNavigationBarViewController.h"

@implementation RLRecyclingRunViewController

@synthesize moneyEarnedLabel;
@synthesize dateTimeLabel;
@synthesize itemArea;

- (RLRecyclingRunViewController *)initWithRun:(RLRecyclingRun *)newRun {
  self=[super init];
  if( self ) {
    run=newRun;
  }
  return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
  [super viewDidLoad];
  
  [self setTitle:@"Recycling Run"];
  
  // Setup the edit button
  self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                                                                       target:self 
                                                                                       action:@selector(showEditRun)];
  
  [self setupItemButtons];
  [self updateDateTimeLabel];
  [self updateMoneyEarnedLabel];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
  [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)updateMoneyEarnedLabel {
  self.moneyEarnedLabel.text=[RLStyleFormatter formatMonetaryValue:run.moneyEarned];
}

- (void)updateDateTimeLabel {
  dateTimeLabel.text=[RLStyleFormatter formatDate:[run dateTime]];
}

- (void)setupItemButtons {
  NSArray *types=[RLRecyclableType listOfficialTypes];
  NSUInteger i=0; // Count number of added buttons to determine layout position
  // for button
  
  NSUInteger BUTTONSPERROW=3;
  CGRect itemAreaFrame=itemArea.frame;
  NSUInteger buttonWidth=itemAreaFrame.size.width/BUTTONSPERROW;
  NSUInteger buttonHeight=buttonWidth; // Make the buttons square
  for(RLRecyclableType *type in types)
  {
    RLRecyclableItem *item=[run itemForUniqueName:type.uniqueName];
    if(item.quantity==0) continue; // Skip empty items
    
    RLRecyclableItemButton *button=[[RLRecyclableItemButton alloc] initWithItem:item];
    button.enabled=NO;
    
    NSUInteger col=i%BUTTONSPERROW;
    NSUInteger row=(i-col)/BUTTONSPERROW;
    [button setFrame:CGRectMake(col*buttonWidth,row*buttonHeight,buttonWidth,buttonHeight)];
    i++;
    
    [itemArea addSubview:button];
  }
  
  NSUInteger totalRows=(i-1-(i-1)%BUTTONSPERROW)/BUTTONSPERROW+1;
  
  [itemArea setContentSize:CGSizeMake(itemAreaFrame.size.width,buttonHeight*totalRows)];
}

- (void)clearItemButtons {
  for(UIView *view in self.itemArea.subviews) {
    [view removeFromSuperview];
  }
}


- (void)showEditRun {
  // Setup undo functionality
  [run.managedObjectContext processPendingChanges];
  [run.managedObjectContext.undoManager beginUndoGrouping];
  
  // Prepare view
  RLEditRecyclingRunViewController *editRecyclingRunViewController=(RLEditRecyclingRunViewController *)[[RLEditRecyclingRunViewController alloc] initWithRun:run];
  
  // Setup responses to the buttons being clicked in the edit run view
  editRecyclingRunViewController.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                                                                 target:self 
                                                                                                                 action:@selector(doneEditingRun)];
  // We have to reaplce the left bar button with a custom button, because
  // the back bar button does not handle any actions. This means that 
  // we loose the arrow shape. :(
  editRecyclingRunViewController.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                                                target:self 
                                                                                                                action:@selector(undoEditingRun)];
  
  // Show view
  [[self navigationController] pushViewController:editRecyclingRunViewController
                                         animated:YES];
  
  // Cleanup
  [editRecyclingRunViewController.navigationItem.rightBarButtonItem release];
  [editRecyclingRunViewController.navigationItem.leftBarButtonItem release];
  [editRecyclingRunViewController release]; 
}

- (void)undoEditingRun {
  [self.navigationController popViewControllerAnimated:YES];
  
  [run.managedObjectContext processPendingChanges];
  [run.managedObjectContext.undoManager endUndoGrouping];
  [run.managedObjectContext.undoManager undoNestedGroup];
}

- (void)doneEditingRun {
  [run.managedObjectContext processPendingChanges];
  [run.managedObjectContext.undoManager endUndoGrouping];
  [self updateMoneyEarnedLabel];
  [self updateDateTimeLabel];
  [self clearItemButtons];
  [self setupItemButtons];
  
  NSError *error;
  if( ![run.managedObjectContext save:&error] ) {
    // TODO Handle error
    NSLog(@"Error saving run.");
  }
  [self.navigationController popViewControllerAnimated:YES];
}


- (void)dealloc {
  [moneyEarnedLabel release];
  [dateTimeLabel release];
  [itemArea release];
  
  [super dealloc];
}


@end
